package org.zfes.snowier.zbss.xzy.biz.vedio.service.impl;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.zfes.snowier.core.data.DataSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.zfes.snowier.core.util.ZBeanUtil;
import org.zfes.snowier.core.util.ZStrUtil;
import org.zfes.snowier.core.util.AppCtxUtil;
import org.zfes.snowier.core.util.FileUtil;
import org.zfes.snowier.core.util.ZAlert;
import org.zfes.snowier.core.util.ZAssert;
import org.zfes.snowier.core.data.ParamMap;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.google.common.collect.Lists;
import org.zfes.snowier.core.data.SelectVo;
import org.zfes.snowier.zbss.xzy.biz.vedio.service.ICloudImageService;
import org.zfes.snowier.zbss.xzy.biz.vedio.dao.CloudImageMapper;
import org.zfes.snowier.zbss.xzy.biz.vedio.model.CloudImage;
import java.util.stream.Stream;
@Service
public class CloudImageServiceImpl implements ICloudImageService{
	private Logger logger =LoggerFactory.getLogger(this.getClass());
 	@Autowired
	private CloudImageMapper cloudImageMapper;
 	ICloudImageService self;
 	
 	private OSSClient ossClient;
	private  String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    private  String accessKeyId = "LTAIHsUzwlidx9MC";
    private  String accessKeySecret = "zurkyY6bNWw74TJ3m2xaeYBiMmn7qU";
    private  String bucketName = "xzyzht";
    
    public ICloudImageService getSelf() {
 		if(self==null) {
 			self=AppCtxUtil.cfg.getBean(ICloudImageService.class);
 		}
		return self;
	}
    private OSSClient getOssClient() {
    	if(ossClient==null) {
    		ossClient = (OSSClient) new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    	}
    	return ossClient;
    }
 	
	@Transactional(rollbackFor=Exception.class)
 	@Override
	public Long createCloudImage(CloudImage cloudImage) {
		ZBeanUtil.setCreateInfo(cloudImage);
		//ZBeanUtil.validateBean(cloudImage);
		cloudImageMapper.insertSelective(cloudImage);
		
		getSelf().uploadCloud(cloudImage);
		return cloudImage.getId();
	}
	
	
	@Async
 	@Override
 	public  void uploadCloud(CloudImage cloudImage) {
 			 String fileName=cloudImage.getFileName();
 			 String filePath=cloudImage.getLocalFilePath();
 			 
 		        try {
 		        	PutObjectResult putResult = getOssClient().putObject(bucketName,  fileName, new File(filePath));
 		        	String requestId = putResult.getRequestId();
 		        	
 		      	 CloudImage  updater = new CloudImage(cloudImage.getId())
		 					.setRequestId(requestId)
		 					.setUploadStatus(Byte.valueOf("1"));
 		      	 updateCloudImage(updater);
 		      	 
	 	 		//FileUtil.deleteFile( filePath);
	 	 		
 		       } catch (OSSException oe ) {
 		    	  logger.error("uploadCloud error:",oe);
 		    	  
	 		    	 CloudImage  updater = new CloudImage(cloudImage.getId())
			 					.setUploadErrorCode(oe.getErrorCode())
			 					.setUploadErrorMsg(oe.getErrorMessage())
			 					.setUploadStatus(Byte.valueOf("0"));
	 		    	updateCloudImage(updater);
 		       } catch (ClientException ce) {
 		    	   
 		    	  logger.error("uploadCloud error:",ce);
 		    	  
	 		    	 CloudImage  updater = new CloudImage(cloudImage.getId())
			 					.setUploadErrorCode(ce.getErrorCode())
			 					.setUploadErrorMsg(ce.getErrorMessage())
			 					.setUploadStatus(Byte.valueOf("0"));
			    	updateCloudImage(updater);
		    	
 		       } finally {
// 		           if (ossClient != null) {
// 		               ossClient.shutdown();
// 		           }
 		       }
	 }
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<CloudImage> loadCloudImageById(Long id) {
		if(id!=null){
			return Optional.ofNullable(cloudImageMapper.selectByPrimaryKey(id));
		}
		return Optional.empty();
		
	}
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<CloudImage> loaByMessageId(Long messageId,Byte status){
		if(messageId!=null){
			return cloudImageMapper.selectByMessageId( messageId,status);
		}
		return Lists.newArrayList();
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void updateCloudImage(CloudImage cloudImage) {
		ZBeanUtil.setUpdatedInfo(cloudImage);
		//ZBeanUtil.validateBean(cloudImage);
		cloudImageMapper.updateByPrimaryKeySelective(cloudImage);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void deleteCloudImage(Long id) {
		ZAssert.notNull(id, "请选择要操作的数据");
		cloudImageMapper.deleteByPrimaryKey(id);
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void setCloudImageStatus(Long id, Byte status) {
		ZAssert.notNull(id, "请选择要操作的数据");
		ZAssert.notNull(status, "状态参数错误");
		if(!Stream.of(new Byte[] {-1,0,1}).anyMatch(val->val.equals(status))) {
			ZAlert.serviceLogicalError("状态参数错误");
		}
		cloudImageMapper.updateStatus( id,  status) ;
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadCloudImageDataSet(Map<String, Object> params) {
		ParamMap pm=ParamMap.filterParam(params);
		DataSet ds=DataSet.newDS2(cloudImageMapper.selectListCount(pm), cloudImageMapper.selectMapListPage(pm));
		return ds;
	}
	
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<SelectVo> loadCloudImageSelectVo(String keywords) {
		if(ZStrUtil.hasText(keywords)) {
			
		}
		List<SelectVo> voList=cloudImageMapper.selectDropList(Byte.valueOf("1"));
		
		return voList==null?Lists.newArrayList():voList;
	}
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<String> loadImageUrl(Long imageId) {
		
		Optional<CloudImage> imgOP =loadCloudImageById(imageId);
		if(!imgOP.isPresent()) {
			return Optional.empty();
		}
		
		String fileName=imgOP.get().getFileName();
	  Date expiration = new Date(new Date().getTime() + 1000 * 60);// 一分钟后过期
	  URL url = getOssClient().generatePresignedUrl(bucketName, fileName, expiration);
	  if (url != null) {
	      return Optional.ofNullable(url.toString());
	  }
	  return Optional.empty();
	}
    
	
}